package com.smaato.gps;

import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.location.*;

public class GPSEngine
{
	private static final int TIMEOUT = 60;
    private static final int PREF_RESPONSE_TIME = TIMEOUT * 1000; // 1 Minute 
    private static final int REQUEST_INTERVAL = 10 * PREF_RESPONSE_TIME; // 10 Minutes
    
    private LocationProvider iProvider = null;
    private QualifiedCoordinates iCoordinates;
    
    private Timer iTimer;

    private class GpsTimerTask extends TimerTask
    {
        public void run()
        {
            doRun();
        }
    };

    public GPSEngine()
    {
        iTimer = new Timer();
        iTimer.schedule(new GpsTimerTask(), 0, REQUEST_INTERVAL);
    }

    public boolean isGPSDataReady()
    {
        return (iCoordinates != null);
    }

    public QualifiedCoordinates getGPSData()
    {
        return iCoordinates;
    }

    public void doRun()
    {   	
        // Create Provider if null
        if (iProvider == null)
        {
            try
            {
                iProvider = LocationProvider.getInstance(null);
            }
            catch (LocationException e)
            {
            }
        }

        if(iProvider != null)
        {
            if(iProvider.getState() == LocationProvider.AVAILABLE)
            {            	
                Location location = null;
                try
                {
                    location = iProvider.getLocation(TIMEOUT * 5); // Timeout of 5 minutes
                } 
                catch (LocationException ex)
                {
                } 
                catch (InterruptedException e)
                {
                }
                
                if(location != null)
                {
                	iCoordinates = location.getQualifiedCoordinates();
                }
            }
        }
    }
}
